import random

blankGameBoard = '''
---------------------
  {}  ｜  {}  ｜ {}
---------------------
  {}  ｜  {}  ｜ {}
---------------------
  {}  ｜  {}  ｜ {}
---------------------
'''


def showGameBoard(board):
    # 打印棋盘
    gameBoard = blankGameBoard.format(
        board[7],
        board[8],
        board[9],
        board[4],
        board[5],
        board[6],
        board[1],
        board[2],
        board[3])
    print(gameBoard)


PLAYER_TURN = 0
COMPUTER_TURN = 1


def firstOne():
    return random.randint(0, 1)


def isPlayAgain():
    print("Do u want to play again?")
    answer = input().lower()
    return answer.startswith('y')


def makeMove(board, move, letter):
    board[move] = letter


def getAllLetter(turn):
    letter = []
    playL = ''
    computerL = ''
    if turn == PLAYER_TURN:
        while not (playL == 'X' or playL == 'O'):
            print("What letter do u want to select?【X, O】")
            # 大写的方式获取字母
            playL = input().upper()
    else:
        playL = random.choice(['X', 'O'])
    if playL == 'X':
        computerL = 'O'
    else:
        computerL = 'X'
    letter.append(playL)
    letter.append(computerL)
    print("你是{},电脑是{}".format(playL, computerL))
    return letter


def getDuplicateBoard(board):
    # 拷贝一个当前面板的数据，方便后续使用且不影响当前的面板（在py中，list所代表的是引用）
    newBoard = board.copy()
    return newBoard


def isFullBoard(board):
    for b in range(0, len(board)):
        if isBlank(board, b):
            return False
    return True


def initBoard():
    board = []
    for i in range(0, 10):
        board.append('')
    return board


def isBlank(board, move):
    # 判断是否是空白的
    return board[move] == ''


def getPlayMove(board, playerLetter):
    # 返回一个int的move 下标
    move = ' '
    while move not in "1 2 3 4 5 6 7 8 9".split(" ") or not isBlank(board, int(move)):
        print("[1-9] choose u move")
        move = input()
    board[int(move)] = playerLetter


"""
AI
"""


def getComputerMove(board, computerLetter, playerLetter):
    # 自动获取电脑的下标
    canMoveList = chooseBlankMoveList(board)
    for i in canMoveList:
        copyBoard = getDuplicateBoard(board)
        copyBoard[i] = computerLetter
        # 如果是机器人
        if isWinner(copyBoard, computerLetter):
            # 优先保证是否获胜
            board[i] = computerLetter
            return
        copyBoard[i] = playerLetter
        # 阻止玩家胜利
        if isWinner(copyBoard, playerLetter):
            board[i] = computerLetter
            return
    board[randomComputerMoveFromList(canMoveList)] = computerLetter


def chooseBlankMoveList(board):
    # 得到可以落子的列表
    blankList = []
    for move in range(0, len(board)):
        if isBlank(board, move):
            blankList.append(move)
    return blankList


def randomComputerMoveFromList(canMoveList):
    if len(canMoveList) != 0:
        return canMoveList[random.randint(0, len(canMoveList) - 1)]


def isWinner(board, letter):
    # 判断胜利标准
    if board[7] == board[8] == board[9] == letter or \
            board[7] == board[4] == board[1] == letter or \
            board[7] == board[5] == board[3] == letter or \
            board[8] == board[5] == board[2] == letter or \
            board[9] == board[6] == board[3] == letter or \
            board[9] == board[5] == board[1] == letter or \
            board[4] == board[5] == board[6] == letter or \
            board[1] == board[2] == board[3] == letter:
        return True
    else:
        return False


if __name__ == '__main__':
    while True:
        computerL = ''
        playerL = ''
        # 正式游戏
        gameBoard = initBoard()
        print("井字棋游戏要开始了～")
        # 随机看是谁先开局
        whoPlay = firstOne()
        playerL, computerL = getAllLetter(whoPlay)
        isPlaying = True

        while isPlaying:
            if whoPlay == PLAYER_TURN:
                getPlayMove(gameBoard, playerL)
                print("玩家：")
                showGameBoard(gameBoard)
                whoPlay = COMPUTER_TURN
                if isWinner(gameBoard, playerL):
                    print("您赢了")
                    isPlaying = False
                    break
            else:
                getComputerMove(gameBoard, computerL, playerL)
                print("电脑：")
                showGameBoard(gameBoard)
                whoPlay = PLAYER_TURN
                if isWinner(gameBoard, computerL):
                    print("电脑赢了")
                    isPlaying = False
                    break
            if isFullBoard(gameBoard):
                print("棋盘满了")
                break

        if not isPlayAgain():
            isPlaying = False
            print("欢迎下次再开始游戏～")
            break
